<!-- 购物车页面 -->
<template>
  <div class="MyCart">
    <!-- 顶部导航栏 吸顶 -->
    <van-sticky>
      <van-nav-bar title="购物车">
        <template #left>
          <van-icon name="arrow-left" color="#fff" @click="goBack">返回</van-icon>
        </template>
      </van-nav-bar>
    </van-sticky>
    <!-- 没有添加东西的时候 -->
    <div v-if="myCart.length === 0">
      <van-empty class="custom-image" :image='emptyShoppingCart' description="购物车空空如也~"/>            
    </div>  
    <div v-else>
      <!-- 加载动画 -->
      <xrzp-Loading v-if="SortDetail.length < myCart.length"></xrzp-Loading>
      <template v-else>
        <van-checkbox-group v-model="result" ref="checkboxGroup">
          <van-swipe-cell v-for="(item,index) in SortDetail" :key="index" class="card">
            <van-card :tag="tag(item)" :title="item.name" 
              :thumb-link="`/sort/sortDetail/${myCart[index].id}`" :num="myCart[index].count"
              :thumb="item.pic" :price="myCart[index].price" :origin-price="myCart[index].originPrice">
              <template #tags>
                <van-tag type="warning" class="mt5 mr10">{{item.tag.split(',')[0]}}</van-tag>
                <van-tag type="warning" class="mr10">{{item.tag.split(',')[1]}}</van-tag>
                <van-tag type="warning" class="mr10">{{item.tag.split(',')[2]}}</van-tag>
                <van-tag type="warning" class="mr10">{{item.tag.split(',')[3]}}</van-tag>
              </template>
              <template #footer>
                <van-button size="mini" @click="decrease(item.id,myCart[index].count)">-</van-button>
                <van-button size="mini" @click="add(item.id)">+</van-button>
              </template>
              <template #bottom>
                <van-checkbox :name="index" class="unchecked" :class="{ checked: result.some(item=>item == index) }">购买</van-checkbox>
              </template>
            </van-card>
            <template #right>
              <van-button square text="加入收藏夹" type="primary" class="delete-button" @click="addFavorite(myCart[index].id)"/>
              <van-button square text="删除商品" type="danger" class="delete-button" @click="del(index)"/>
            </template>
          </van-swipe-cell>
        </van-checkbox-group>

        <!-- 底部提交订单按钮 -->
        <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit">
          <van-checkbox v-model="check" @click="checkAll" class="unchecked" :class="{ checked: result.length === myCart.length }">全选</van-checkbox>
        </van-submit-bar>

        <!-- 付款弹窗 -->
        <van-dialog v-model="show" title="付款确认" show-cancel-button @confirm="buy" @cancel="notBuy" class="popup">
          <div class="introduction">个人钱包: <span>¥{{ remainingSum.toFixed(2) }}</span> </div>
          <div class="introduction">商品价格: <span>¥{{ (total/100).toFixed(2) }}</span> </div>
          <div class="introduction">下单后余额: <span>¥{{ (remainingSum-total/100).toFixed(2) }}</span> </div>
        </van-dialog>
      </template>
    </div>

    <!-- 底部选项卡 -->
    <xrzp-FootTabbar></xrzp-FootTabbar>
  </div>
</template>

<script>
import { axios_detail } from "@/api/data_axios";
import image from '@/assets/image';
import { Dialog,Toast } from 'vant';
import { mapState } from "vuex";
export default {
  data(){
    return{
      emptyShoppingCart:image.emptyShoppingCart,
      SortDetail:[],
      appkey:"13e76141171ebe61f22e24477b559988",
      check:false,        // 全选按钮状态
      result:[],          // 选中的按钮集合
      show:false,         // 付款 订单 弹窗
    }
  },
  computed:{
    ...mapState(["myCart","favorite","remainingSum"]),
    // 图片角标 闭包解决 v-for循环 计算属性 item 取不到的问题
    tag(){
      return (item)=>{
        return item.tag.split(',').length > 5 ?'火爆':'推荐';
      }
    },
    // 监听选择项 计算合计价格
    total(){
      if (this.result.length) {
        let sum = 0;
        this.result.forEach(item=>{
          sum += this.myCart[item].count * this.myCart[item].price;      
        })
        return sum*100;
      } else {
        return 0;
      }
    },
  },
  watch:{
    // 单选全部后触发全选
    result(){
      this.check = this.result.length === this.myCart.length;
    }
  },
  mounted(){
    this.getData();
  },
  methods:{
    // 请求数据  同步请求数据(async await)
    async getData(){
      for(let index=0 ;index < this.myCart.length ; index++ ){
        let data = {
          id:this.myCart[index].id,
          appkey:this.appkey
        }
        let res = await axios_detail(data);
        this.SortDetail.push(res.result.result);
      }
    },
    // 全选 反选
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(this.check);
    },
    // 加 购物车
    add(id){
      this.$store.commit("addCart",id);
    },
    // 减 购物车
    decrease(id,num){
      this.$store.commit("decreaseCart",id);
      if (num===1) {
        this.$router.go(0);
      }
    },
    // 删除 购物车
    del(index){
      this.$store.commit("delCart",index);
      this.$router.go(0);
    },
    // 加入收藏夹
    addFavorite(val) {
      let id = val+"";
      if (this.favorite.indexOf(id) === -1) {
        Toast.success('添加成功');
        this.$store.commit("addFavorite",id);
      } else {
        Toast.fail('收藏夹已存在该商品');
      }
    },
    // 提交订单
    onSubmit(){
      if (this.result.length) {
        if (this.remainingSum - this.total/100 >= 0) {
          this.show=!this.show;
        }else{
          Dialog.alert({
            title: '提示',
            message: '钱包余额不足',
            theme: 'round-button',
            confirmButtonText:'去充值',
          }).then(() => {
            this.$router.push({ path: "/wallet" });
          });
        }
      }else{
        Toast.fail('未选择商品,不能提交订单');
      }
    },
    // 购买
    buy(){
      let time = this.$moment(new Date()).format("YYYY年MM月DD日 HH:mm");
      let time1 = this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      let arr = [];
      for (let index = 0; index < this.result.length; index++) {
        arr.push({ name:this.SortDetail[this.result[index]].name,num:this.myCart[this.result[index]].count,price: this.myCart[this.result[index]].price})
      }
      let details={
            time:time1,
            commodity:arr
          }
      this.$store.commit("addBill", [0,this.total/100*-1,"消费 - 购物消费",time,details]);
      this.$store.commit("addMoney", this.total/100*-1);
      this.$store.commit("buyCart",this.result);
      Dialog.alert({
        title: '提示',
        message: '下单成功',
        theme: 'round-button',
      }).then(() => {
        this.$router.go(0);
      });
    },    
    // 未购买
    notBuy(){
      Dialog.alert({
        title: '提示',
        message: '未购买',
        theme: 'round-button',
      })
    },  
    // 返回
    goBack() {
      this.$router.go(-1);
    },
  }
}
</script>

<style lang="scss" scoped>
.MyCart{
  .van-nav-bar {
    background-color: $base-color;
    ::v-deep .van-nav-bar__title{
      font-weight: bold;
    }
    .van-icon{
      font-weight: bold;
    }
  }
  .van-card__title{
    font-size: 15px;
    font-weight: bold;
    line-height: 20px;
  }
  .van-empty{
    padding: 30% 0;
  }
  .custom-image{
    ::v-deep .van-empty__image {
      width: 240px;
      height: 240px;
    }
  }
  .van-card__title{
    font-size: 15px;
    font-weight: bold;
    line-height: 20px;
  }
  .checked{
    ::v-deep .van-checkbox__label{
      color: #1989fa;
    }
  }
  .unchecked{
    ::v-deep .van-checkbox__label{
      font-weight: bold;
      font-size: 15px;
    }
  }
  .van-card__price{
    color: red;
    font-weight: bold;
  }
  .delete-button {
    height: 100%;
  }
  .van-button--normal{
    font-weight: bold;
  }
  .van-checkbox-group{
    margin-bottom: 100px;
    .card{
      .van-card__footer {
        position: absolute;
        top: 74px;
        right: -16px;
      }
      .van-button--mini {
        padding: 0 5px;
        font-size: 15px;
        width: 22px;
        margin-right: 24px;
      }
      .van-card__num {
        margin-right: 16px;
        font-size: 15px;
        margin-top: 20px;
        width: 24px;
        text-align: center;
        color: #323233;
      }
      &:last-child{
        margin-bottom: 50px;
      }
    }
  }
  .popup{
    font-weight: bold;
    ::v-deep .van-dialog__header{
      font-weight: bold;
    }
    .introduction{
      text-align: center;
      margin-top: 5px;
      font-weight: 500;
      span{
        color: red;
        font-weight: bold;
      }
    }
    div:last-child{
      margin-bottom: 10px;
    }
  }
  .van-submit-bar{
    margin-bottom: 48px;
    background-color: cornsilk;
  }
}
</style>
